/* eslint-disable @typescript-eslint/no-explicit-any */
import {defineStore} from 'pinia'
import {_userLogin, _getUserInfo, _userLogout, _fetchRoutesFromBackend} from '@/api/generic/login/login-api'
import { authStore } from '@/stores/authStore'
import type { LoginFormVo } from '@/views/login/LoginForm'
import { moduleStore } from './moduleStore'
import { _getAllSystemCode } from '@/api/generic/code/code-api'
import { codeStore } from './codeStore'
import {setupDynamicRoutes} from "@/router";
//登录返回结果集
export interface LoginResult {
  tokenValue:string,
  message: string,
  code: number
}
const fetchRoutesFromBackend = async () => {
  const response = await _fetchRoutesFromBackend();
  return response.data;
};
export const userAuthProcessStore = defineStore('userAuthProcessStore', {
//"tokenValue":"5208a4d5-1eb3-4144-a352-d822a404b6ea" ; token
//loginId" : '123123123213' //userid
  actions: {

    //账号登录
   async Login_Account(loginForm: LoginFormVo)
   {
    const store = authStore();
      const res = await _userLogin(loginForm);
      if(!res){
        return Promise.reject("GET Token Error");
      }
      if(res.code != 200){
        console.error("登录错误：")
        console.error(res.message);
        if(res.message){
          return Promise.reject(res.message);
        }
        return Promise.reject("GET Token Error");
      }
      console.log("token:" + res.data.tokenValue);

      store.SET_TOKEN(res.data.tokenValue);
     await setupDynamicRoutes();
    },


    //获取用户信息
    async Get_UserInfo()
    {
      const store = authStore();
      if(!store.getToken){
        return Promise.reject("undefinded token")
      }
      const res = await _getUserInfo();
      console.log(res)
      if(res && res.data && res.data.systemUserRespVO){
        store.SET_USERINFO(res.data.systemUserRespVO).then(()=>{
          const modelStores = moduleStore();
          modelStores.reloadModuleInfos(res.data.moduleRespVOList,res.data.menuTreeRespVOList);
          //TODO cache user
          return Promise.resolve();
        }).catch(err=>{
          console.error(err);
          return Promise.reject("UserInfo UnValidate");
        });
      }else{
        return Promise.reject("UserInfo UnValidate");
      }
    },

    //获取码表数据
    async GET_CODE(){
      const store = codeStore();
      const res = await _getAllSystemCode();
      if(res && res.data){
        console.log(res.data);
        console.log("store，codes");
        store.setInfoBySystemCode(res.data);
      }
    },


    //退出登录 . 若不传url path  则仅清token数据
    async Logout()
    {
      const store = authStore();
      const codeStores = codeStore();
      await _userLogout().catch((res)=>{console.error(res)}).finally(()=>{
        store.CLEAR_USERINFO();
        store.REMOVE_TOKEN();
        codeStores.clearCodeCache();
        const moduleStoreInstance = moduleStore(); // Renamed to avoid conflict
        moduleStoreInstance.clearModuleMap()
      })
    }
  }
})


